package org.boulderfoodrescue.webapp.client.pickups.selectors;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasValue;

public class CustomSelector<T> extends FlowPanel implements HasValue<T>{
	private CustomSelectorView view;
	private T value;
	private SelectorInterface<T> selectorInterface;
	public CustomSelector(final SelectorInterface<T> selectorInterface, String attribute){
		this.selectorInterface = selectorInterface;
		view = new CustomSelectorView(attribute);
		view.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				CustomSelectorDialog<T> dlg;
				if(view != null)
					dlg = new CustomSelectorDialog<T>(selectorInterface,value);
				else
					dlg = new CustomSelectorDialog<T>(selectorInterface);
				dlg.center();
				dlg.addHandler(new ValueChangeHandler<T>(){
					@Override
					public void onValueChange(ValueChangeEvent<T> event) {
						setValue(event.getValue());
					}
				}, ValueChangeEvent.getType());
			}
		});
		this.add(view);
	}
	@Override
	public HandlerRegistration addValueChangeHandler(
			ValueChangeHandler<T> handler) {
		return addHandler(handler, ValueChangeEvent.getType());
	}
	@Override
	public T getValue() {
		return value;
	}
	@Override
	public void setValue(T value) {
		setValue(value, true);
	}
	@Override
	public void setValue(T value, boolean fireEvents) {
		this.value = value;
		if(fireEvents)
			ValueChangeEvent.fire(this, value);
		selectorInterface.setValue(value);
		view.setText(selectorInterface.getValueAsString());
	}
	
	@Override
	public void clear(){
		selectorInterface.clear();
	}
	
	public void setEnabled(Boolean enabled){
		view.setEnabled(enabled);
	}
	
	public void addEntry(T entry) {
		selectorInterface.addEntry(entry);
	}
	
	public void removeEntry(T entry){
		selectorInterface.removeEntry(entry);
	}
	
	public void updateEntry(){
		selectorInterface.refreshEntries();
	}

}
